<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Wxpay;
use app\common\model\Admin;
use app\common\model\Article;
use app\common\model\Attention;
use app\common\model\Order;
use app\common\model\User;
use PosterMaker\PosterMaker;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['index', 'user_info', 'article_list', 'composite'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $param = request()->param();
        extract($param);
        if (!$id) {
            $this->error('文章不存在');
        }
        $uid = $this->auth->id;
        $article = new Article;
        $data = $article->get($id, ['admin', 'user']);
        if (!$data) {
            $this->error('文章已下架');
        }
        if (!$uid) {
            if ($data->status == 'normal' && $data->state == '1' && $data->switch == 1) {
                if ($data->pay_price > 0) {
                    $data->pay_status = 0;
                    $data = $data->hidden(['content']);
                } else {
                    $data->pay_status = 1;
                }
            } else {
                if ($data->pay_price > 0 && $data->state != '1' && $data->switch != 1) {
                    if ($data->state != '1' || $data->switch != 1) {
                        $data->pay_status = 0;
                        $data = $data->hidden(['content']);
                    }
                } else {
                    $data->pay_status = 1;
                }
            }
        } else {
            $order = new Order();
            $num = $order->where('user_id', $uid)->where('status', '1')->where('article_id', $id)->count();

            if ($num > 0) {
                $data->pay_status = 1;
            } else {

                if ($data->status == 'normal' && $data->state == '1' && $data->switch == 1) {
                    $data->pay_status = 1;
                } else {
                    if ($data->pay_price > 0) {
                        if ($data->state != '1' || $data->switch != 1) {
                            $data->pay_status = 0;
                            $data = $data->hidden(['content']);
                        }
                    } else {
                        $data->pay_status = 1;
                    }
                }
            }
        }
        $this->success('请求成功', $data);
    }

    /**
     * 作者
     *
     */
    public function user_info()
    {
        $param = request()->param();
        extract($param);
        $admin = new User();
        $article = new Article;
        $uid = $this->auth->id;
        $data = $admin->get($id)->visible(['nickname', 'bio', 'avatar', 'normal_num', 'expire_num', 'gz']);
        $data->normal_num = $article->where('status', 'normal')->where('user_id', $id)->count();
        $data->expire_num = $article->where('status', 'hidden')->where('user_id', $id)->count();
        $data->gz = Attention::where(['user_id' => $uid, 'admin_id' => $id])->count();
        $this->success('请求成功', $data);
    }

    /**
     * 作者文章
     *
     */
    public function article_list()
    {
        $param = request()->param();
        extract($param);
        $article = new Article;
        $article->where('user_id', $id);
        $article->order('id desc');
        if ($type == 1) {
            $article->where('status', 'normal');
        } else {
            $article->where('status', 'hidden');
        }
        $list = $article->paginate();
        foreach ($list as $k => $v) {
            $v->hidden(['content']);
        }
        $this->success('请求成功', $list);
    }
    /**
     * 关注
     *
     */
    public function gz()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $attention = new Attention;
        $data = $attention->get(['user_id' => $uid, 'admin_id' => $id]);
        if ($data) {
            $attention->where(['id' => $data->id])->delete();
        } else {
            $attention->save(['user_id' => $uid, 'admin_id' => $id]);
        }
        $this->success('');
    }

    /**
     * 文章支付
     *
     */
    public function pay_order()
    {
        $param = request()->param();
        extract($param);
        $uid = $this->auth->id;
        $article = new Article;
        $article = $article->get($article_id);
        if (!$article || $article->status == 'hidden') {
            $this->error('文章已下架');
        }
        $data = [
            'sn' => sn('order', 'sn', 'SN'),
            'user_id' => $uid,
            'article_id' => $article_id,
            'pay_money' => $article->pay_price,
        ];
        $userInfo = User::get($uid);
        Db::startTrans();
        try {
            $order = new Order();
            $orders = $order->allowField(true)->save($data);
            if ($orders) {

                if ($data['pay_money'] <= 0) {
                    $order->save(['status' => 1, 'paytime' => time()]);
                } else {
                    $sdk = Wxpay::wxpay($data['sn'], $data['pay_money'], $userInfo['openid']);
                }
            } else {
                exception('购买失败');
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        queue('app\model\job\Order', $order, 1800);
        $this->success('', $sdk ?? []);
    }

    /**
     * 发布文章
     *
     */
    public function addArticle()
    {
        $params = request()->param();
        extract($params);
        if (!isset($title) || !$title) {
            $this->error('标题不能为空');
        }

        if (!isset($content) || !$content) {
            $this->error('内容不能为空');
        }
        // if (!isset($bgid) || $bgid) {
        //     $this->error('请选择模板');
        // }
        // if (!isset($opentime) || !$opentime) {
        //     $this->error('公开时间不能为空');
        // }
        // if (!isset($endtime) || !$endtime) {
        //     $this->error('结束时间不能为空');
        // }
        if (!empty($images)) {
            $arr = explode(',', $images);
            $count = count($arr);
        }
        Db::startTrans();
        try {
            $params['user_id'] = $this->auth->id;
            $params['images_num'] = $count ?? 0;
            $params['text_num'] = subHtmlChars($content);
            $params['opentime'] = strtotime($opentime);
            $params['endtime'] = strtotime($endtime);
            $Article = new Article($params);
            $Article->allowField(true)->save();
            $bgimages = config('site.share_images');
            $logo = config('site.logo');
            $name = config('site.name');
            $shareImg = composite($bgimages[$bgid], build(cdnurl("?id={$Article->id}", true)), $title, $description, $logo, $name, $pay_price, $returns);
            $Article->share_image = $shareImg;
            $Article->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功', Article::get($Article->id));
    }


    /**
     * 文章管理
     *
     */
    public function lists()
    {
        $param = request()->param();
        extract($param);
        $article = new Article();
        if (isset($keywords) && $keywords) {
            $article->whereLike('title', '%' . $keywords . '%');
        }
        $list = $article->where('user_id', $this->auth->id)->order('id desc')->paginate();
        $this->success('', $list);
    }
    /**
     * 文章公开
     *
     */
    public function open()
    {
        $param = request()->param();
        extract($param);
        $data = Article::get($id);
        if ($data) {
            $data->save(['state' => $state]);
        }
        $this->success('成功');
    }
}
